package com.softwinner.bt.policy;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.security.InvalidParameterException;

import com.softwinner.bt.util.BTLog;
import com.softwinner.bt.util.Command;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.*;
import android_serialport_api.SerialPort;

public class BTManager {
	private static final String TAG = "BTManager";	
	public static boolean IsBtWifiCombo = false;
    private static SerialPort mSerialPort;
    private static OutputStream mOutputStream;
    private static BTManager mBTManager;
    
    public static final int STATE_OPENING = 0;
    public static final int STATE_UNCONNECTION = 1;
    public static final int STATE_CONNECTING = 2;
    public static final int STATE_CONNECTED = 3;
    public static final int STATE_CALLING = 4;
    public static final int STATE_INCOMINGCALL = 5;
    public static final int STATE_INCALL = 6;
    public static final int STATE_CLOSED = 7;

    public static BTManager getInstance() {
        if (mBTManager == null) {
        	mBTManager = new BTManager();
        }
        return mBTManager;
    }

    private BTManager() {}
    /**
     * 初始化串口
     * @return
     * @throws SecurityException
     * @throws IOException
     * @throws InvalidParameterException
     */
    public static SerialPort getSerialPort() throws SecurityException,
            IOException, InvalidParameterException {
        if (mSerialPort == null) {
            String path = "/dev/ttyS7";
			if(IsBtWifiCombo){
				path = "/dev/goc_serial";
			}
            int baudrate = Integer.decode("9600");// 115200
            if ((path.length() == 0) || (baudrate == -1)) {
                throw new InvalidParameterException();
            }

            try {
                mSerialPort = new SerialPort(new File(path), baudrate, 0);
                mOutputStream = mSerialPort.getOutputStream();
            } catch (Exception e) {
            	Log.e(TAG,"getSerialPort error"+e.getLocalizedMessage());
            }
        }
        return mSerialPort;
    }
    /**
     * 关闭串口
     */
    public void closeSerialPort() {
        if (mSerialPort != null) {
            mSerialPort.closePort();
            mSerialPort = null;
        }
    }
	/**
	 * 往蓝牙模块发送指令
	 * @param command 指令字符，一般是以AT#开头
	 */
    public void sendCommand(String command) {
        Log.i("Send", "" + command);
        try {
            mOutputStream.write(command.getBytes());
            mOutputStream.write(new String(Command.SEND_END_COMMIT)
                    .getBytes());
            mOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
